import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { Text, View, StyleSheet, Alert, Image, ActivityIndicator, ScrollView } from 'react-native';
import { Icon, List, ListItem, Button, FormInput, CheckBox } from 'react-native-elements';
import Loader from './widgets/Loader';
import { clearStorage } from './clientStorage';
import { NavigationActions } from 'react-navigation';
import { executor, primaryColor, toast, uploadImage } from './utils';
import ImagePicker from 'react-native-image-crop-picker';

const styles = StyleSheet.create({
  marginTop: {
    marginTop: 16
  },
  right: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center'
  },
  image: {
    width: 50,
    height: 50
  },
  list: {
    marginTop: 0
  },
  header: {
    padding: 12
  }
});

class OrderNotePage extends Component {
  static navigationOptions = ({screenProps, navigation}) => {
    return {
      title: `Order #${navigation.state.params.displayId}`,
    };
  }
  state = { notes: [] }
  onSelectNote = (note) => {
    const index = this.state.notes.indexOf(note);
    if (index < 0) {
      this.setState({notes:[...this.state.notes, note]});
    } else {
      this.setState({notes:[...this.state.notes.slice(0,index), ...this.state.notes.slice(index+1)]});
    }
  }
  onCallLog = () => this.onChoose('callLogUri')
  onPhotoProof = () => this.onChoose('photoProofUri')
  onChoose = (key) => {
    Alert.alert(
      `Options`,
      null,
      [
        {text: 'Take Photo', onPress: () => {
          ImagePicker.openCamera({width: 400,
            height: 400})
            .then(({path}) => this.setState({[key]: path}));
        }},
        {text: 'Select From Gallery', onPress: () => {
          ImagePicker.openPicker({width: 400,
            height: 400,})
            .then(({path}) => this.setState({[key]: path}))
        }},
      ],
      { cancelable: true }
    );
  }
  onSubmit = () => {
    const { notes, callLogUri, photoProofUri } = this.state;
    if (notes.length===0) return toast('Please select a reason');
    if (!callLogUri) return toast('Please add a call log screenshot');

    const { pickupFailed, deliveryFailed } = this.props.navigation.state.params;

    executor((pickupFailed&&this.props.pickupFailed)||(deliveryFailed&&this.props.deliveryFailed), {note: notes.join(', '), callLogUri, photoProofUri})
      .then(({res}) => {
        this.setState({processing: false});
        if (res) {
          toast('Success');
          this.props.navigation.goBack();
        }
      });
    this.setState({processing: true});
  }
  render() {
    const { pickupFailed, deliveryFailed } = this.props.navigation.state.params;
    const { loading, remarks } = this.props;
    const { notes, callLogUri, photoProofUri } = this.state;
    if (loading) return <Loader/>;

    return (
      <ScrollView>
        <Text style={styles.header}>Select Reason</Text>
        <List containerStyle={styles.list}>
          {remarks&&
            remarks.map((remark, index) => <ListItem title={remark.description} onPress={()=>this.onSelectNote(remark.description)}
              rightIcon={{name:notes.indexOf(remark.description)>=0?'check-box':'check-box-outline-blank',
                color:notes.indexOf(remark.description)>=0?primaryColor:null}}/>)
          }
        </List>
        <Text style={styles.header}>Call Log</Text>
        <List containerStyle={styles.list}>
          <ListItem avatar={{uri:callLogUri}} title='Click to add call log screenshot'
            onPress={this.onCallLog}/>
        </List>
        <Text style={styles.header}>Photo Proof</Text>
        <List containerStyle={styles.list}>
          <ListItem avatar={{uri:photoProofUri}} title='Click to take a photo'
            onPress={this.onPhotoProof}/>
        </List>
        {this.state.processing?<ActivityIndicator style={styles.marginTop}/>:
          <View style={styles.marginTop}>
            <Button title='Submit' backgroundColor={primaryColor}
              onPress={this.onSubmit}/>
          </View>
        }
      </ScrollView>
    );
  }
}

export default compose(
  graphql(gql`
    query FailedRemarks {
      remarks(type:"pickupdeliveryfailed") {
        id
        description
      }
    }
  `, {
    props: ({data:{remarks, loading}}) => {
      return {
        remarks,
        loading
      };
    }
  }),
  graphql(gql`
    mutation pickupFailed($orderId:String!,$note:String!) {
      pickupFailed(orderId:$orderId,note:$note) {
        id
        status {
          statusId
        }
      }
    }
  `, {
    name: 'pickupFailed',
    props: ({ownProps:{navigation:{state:{params:{id}}}}, pickupFailed}) => {
      return {
        pickupFailed: ({note, callLogUri, photoProofUri}) => {
          return Promise.all([
              callLogUri&&uploadImage(callLogUri),
              photoProofUri&&uploadImage(photoProofUri),
            ])
            .then(results => {
              const callLog = results[0];
              const photoProof = results[1];

              return pickupFailed({
                variables: {
                  note: `${note}${callLog?`\nCall Log:\n${callLog.data}`:''}${photoProof?`\nPhoto Proof:\n${photoProof}`:''}`,
                  orderId: id
                }
              });
            });
        }
      };
    }
  }),
  graphql(gql`
    mutation deliveryFailed($orderId:String!,$note:String!) {
      deliveryFailed(orderId:$orderId,note:$note) {
        id
        status {
          statusId
        }
      }
    }
  `, {
    name: 'deliveryFailed',
    props: ({ownProps:{navigation:{state:{params:{id}}}}, deliveryFailed}) => {
      return {
        deliveryFailed: ({note, callLogUri, photoProofUri}) => {
          return Promise.all([
              callLogUri&&uploadImage(callLogUri),
              photoProofUri&&uploadImage(photoProofUri),
            ])
            .then(results => {
              const callLog = results[0];
              const photoProof = results[1];

              return deliveryFailed({
                variables: {
                  note: `${note}${callLog?`\nCall Log:\n${callLog.data}`:''}${photoProof?`\nPhoto Proof:\n${photoProof.data}`:''}`,
                  orderId: id
                }
              });
            });
        }
      };
    }
  })
)(OrderNotePage);

